package days45.title160;

import days38.title2.ListNode;

import java.util.HashSet;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode nodeA = headA;
        ListNode nodeB = headB;
        HashSet<ListNode> listNodes = new HashSet<>();
        while (true) {
            if (nodeA == null && nodeB == null) {
                break;
            }
            if (nodeA != null) {
                boolean add = listNodes.add(nodeA);
                if (!add) {
                    return nodeA;
                }
                nodeA = nodeA.next;
            }
            if (nodeB != null ){
                boolean add = listNodes.add(nodeB);
                if (!add) {
                    return nodeB;
                }
                nodeB = nodeB.next;
            }
        }
        return null;
    }
}